<template>
    <el-card shadow="never">
        <template #header>
            <div class="d-flex justify-content-between align-items-center">
                <h5>我的消息</h5>
                <div>
                    <el-radio-group v-model="filter" size="small" @change="handleFilterChange">
                        <el-radio-button label="all">全部</el-radio-button>
                        <el-radio-button label="unread">未读</el-radio-button>
                    </el-radio-group>
                </div>
            </div>
        </template>

        <el-row :gutter="20">
            <!-- 消息列表 -->
            <el-col :span="8" class="message-list-container">
                <el-scrollbar>
                    <div v-if="messages.length > 0">
                        <div v-for="msg in sortedMessages" :key="msg.message.id" class="message-item"
                            :class="{ 'is-unread': !msg.message.isRead, 'is-active': selectedMessage?.message.id === msg.message.id }"
                            @click="selectMessage(msg)">
                            <div class="d-flex align-items-start">
                                <el-icon class="message-icon" :size="20">
                                    <component :is="getMessageIcon(msg.message.messageType)" />
                                </el-icon>
                                <div class="message-content">
                                    <p class="message-title" :class="{ 'fw-bold': !msg.message.isRead }">
                                        <span v-if="!msg.message.isRead" class="unread-dot"></span>
                                        {{ generateMessageTitle(msg) }}
                                    </p>
                                    <p class="message-summary text-muted">
                                        {{ generateMessageSummary(msg) }}
                                    </p>
                                    <small class="text-muted">{{ dayjs(msg.message.createdAt).fromNow() }}</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <el-empty v-else description="暂无消息" />
                </el-scrollbar>
            </el-col>

            <!-- 消息详情 -->
            <el-col :span="16" class="message-detail-container">
                <div v-if="selectedMessage">
                    <div class="detail-header mb-3">
                        <h6 class="mb-1">{{ generateMessageTitle(selectedMessage) }}</h6>
                        <small class="text-muted">{{ dayjs(selectedMessage.message.createdAt).format('YYYY-MM-DD HH:mm')
                        }}</small>
                    </div>
                    <div class="detail-content">
                        <!-- 帖子被回复 -->
                        <div v-if="selectedMessage.message.messageType === 2">
                            <p>您的帖子 <el-tag size="small">{{ selectedMessage.post?.title }}</el-tag> 收到了新的回复：</p>
                            <el-card shadow="never" class="mt-2">"{{ selectedMessage.reply?.content }}"</el-card>
                        </div>
                        <!-- 回复被回复 -->
                        <div v-if="selectedMessage.message.messageType === 3">
                            <p>您在帖子 <el-tag size="small">{{ selectedMessage.post?.title }}</el-tag> 中的评论收到了新的回复：</p>
                            <div class="reply-chain">
                                <el-card shadow="never" class="my-2">
                                    <p class="text-muted mb-1">您的评论：</p>
                                    <p class="mb-0">"{{ selectedMessage.fatherReply?.content }}"</p>
                                    <el-tag v-if="selectedMessage.fatherReply?.isDelete" type="info" size="small"
                                        class="mt-1">此评论已删除</el-tag>
                                </el-card>
                                <el-card shadow="never" class="my-2">
                                    <p class="text-muted mb-1">来自用户 {{ selectedMessage.message.senderId }} 的回复：</p>
                                    <p class="mb-0">"{{ selectedMessage.reply?.content }}"</p>
                                    <el-tag v-if="selectedMessage.reply?.isDelete" type="info" size="small"
                                        class="mt-1">此回复已删除</el-tag>
                                </el-card>
                            </div>
                        </div>
                        <!-- 帖子被删除 -->
                        <div v-if="selectedMessage.message.messageType === 1">
                            <p>您的帖子 <el-tag type="info" size="small">{{ selectedMessage.post?.title }}</el-tag> 已被管理员删除。
                            </p>
                            <el-card shadow="never" class="mt-2">
                                <p class="mb-1"><strong>删除原因：</strong></p>
                                <p class="mb-0">{{ selectedMessage.message.extraData?.reason || '未提供原因' }}</p>
                            </el-card>
                        </div>
                        <!-- 回复被删除 -->
                        <div v-if="selectedMessage.message.messageType === 4">
                            <p>您在帖子 <el-tag size="small">{{ selectedMessage.post?.title || '（帖子已不存在）' }}</el-tag>
                                中的一条评论已被管理员删除。
                            </p>
                            <el-card shadow="never" class="mt-2">
                                <p class="text-muted mb-1">被删除的评论内容：</p>
                                <p class="mb-0">"{{ selectedMessage.reply?.content }}"</p>
                            </el-card>
                            <el-card shadow="never" class="mt-2">
                                <p class="mb-1"><strong>删除原因：</strong></p>
                                <p class="mb-0">{{ selectedMessage.message.extraData?.reason || '未提供原因' }}</p>
                            </el-card>
                        </div>
                    </div>
                    <div class="detail-actions mt-4">
                        <el-button type="primary" @click="goToLocation" :disabled="!canGoToLocation">
                            <i class="bi bi-pin-map-fill me-1"></i> 跳转到具体位置
                        </el-button>
                        <el-button type="danger" plain @click="deleteMessage">删除此消息</el-button>
                    </div>
                </div>
                <el-empty v-else description="请选择一条消息查看详情" />
            </el-col>
        </el-row>
    </el-card>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useForumStore } from '@/stores/forum.js';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';
import { ChatDotRound, Comment, Delete, Finished } from '@element-plus/icons-vue';

dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

const forumStore = useForumStore();
const router = useRouter();
const { messages, totalMessages } = storeToRefs(forumStore);

const filter = ref('all'); // 'all' or 'unread'
const selectedMessage = ref(null);
const sortedMessages = computed(() => {
    if (!messages.value) return [];

    // 创建一个可变副本进行排序，避免直接修改 store 中的状态
    return [...messages.value].sort((a, b) => {
        // 规则1：未读消息优先于已读消息
        if (a.message.isRead !== b.message.isRead) {
            return a.message.isRead - b.message.isRead; // isRead: 0 (未读) 会排在 1 (已读) 前面
        }
        // 规则2：如果已读状态相同，则按创建时间降序排列（最新的在最前）
        return new Date(b.message.createdAt) - new Date(a.message.createdAt);
    });
});
const emit = defineEmits(['navigate-to-post']);

const handleFilterChange = () => {
    selectedMessage.value = null; // 切换时清空详情
    const params = { pageSize: -1 };
    if (filter.value === 'unread') {
        params.isRead = 0;
    }
    forumStore.fetchMessages(params);
};

const selectMessage = (msg) => {
    selectedMessage.value = msg;
    // 如果消息是未读的，则调用接口标记为已读
    if (!msg.message.isRead) {
        forumStore.markMessageAsRead(msg.message.id);
    }
};

const getMessageIcon = (type) => {
    const iconMap = {
        1: Delete,
        2: ChatDotRound,
        3: Comment,
        4: Delete,
    };
    return iconMap[type] || Finished;
};

const generateMessageTitle = (msg) => {
    const typeMap = {
        1: '您的帖子被删除',
        2: '您收到了新的帖子回复',
        3: '您收到了新的评论回复',
        4: '您的评论被删除',
    };
    return typeMap[msg.message.messageType] || '系统通知';
};

const generateMessageSummary = (msg) => {
    switch (msg.message.messageType) {
        case 1: return `帖子: ${msg.post?.title || '未知'}`;
        case 2: return `来自用户 ${msg.message.senderId} 的回复`;
        case 3: return `来自用户 ${msg.message.senderId} 的回复`;
        case 4: return `评论内容: "${(msg.reply?.content || '').substring(0, 20)}..."`;
        default: return '点击查看详情';
    }
};

const canGoToLocation = computed(() => {
    if (!selectedMessage.value) return false;
    // 只有回复类消息可以跳转
    const type = selectedMessage.value.message.messageType;
    return (type === 2 || type === 3) && selectedMessage.value.post && !selectedMessage.value.post.isDelete;
});

const goToLocation = () => {
    if (!canGoToLocation.value) return;
    const msg = selectedMessage.value;

    // 1. 在 store 中设置导航目标
    forumStore.setNavigationTarget({
        postId: msg.post.id,
        replyId: msg.reply?.id
    });

    // 2. 跳转到社区页面，让 Community.vue 来处理后续逻辑
    router.push('/community');
};

const deleteMessage = () => {
    if (!selectedMessage.value) return;
    forumStore.deleteMessage(selectedMessage.value.message.id, () => {
        selectedMessage.value = null; // 删除后清空详情
    });
};
</script>

<style scoped>
.message-list-container {
    height: 60vh;
    border-right: 1px solid var(--el-border-color-light);
}

.unread-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    background-color: var(--el-color-danger);
    border-radius: 50%;
    margin-right: 6px;
    vertical-align: middle;
    /* 确保红点和文字垂直居中对齐 */
}

.message-title {
    display: flex;
    align-items: center;
}

.message-item {
    padding: 12px;
    cursor: pointer;
    border-bottom: 1px solid var(--el-border-color-lighter);
}

.message-item:hover {
    background-color: var(--el-fill-color-light);
}

.message-item.is-active {
    background-color: var(--el-color-primary-light-9);
}

.message-item.is-unread .message-title {
    font-weight: bold;
    color: var(--el-text-color-primary);
}

.message-icon {
    margin-right: 12px;
    color: var(--el-text-color-secondary);
}

.message-content p {
    margin: 0;
    line-height: 1.4;
}

.message-title {
    font-size: 14px;
}

.message-summary {
    font-size: 13px;
}

.message-detail-container {
    padding: 12px 24px;
}

.reply-chain .el-card {
    background-color: #f9f9f9;
}
</style>
